package cn.org.wifit.core.zookeeper.watcher;

import java.util.regex.Pattern;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.Watcher.Event.EventType;

import cn.org.wifit.core.zookeeper.NodeReadWatcherHandle;

/**
 * Zookeeper上IMUser节点状态的管理器，用途包括：
 * 监听zookeeper节点上的IMUser节点的变化：<br>
 * 1、以便在IMUser各属性变化后，更新本地内存中的IMUser的相关信息。<br>
 * 2、以便在IMUser个子节点变化后，更新本地内存中的IMUser的相关信息。
 * @author yinwenjie
 */
public class IMUserWatcher implements Watcher {
	private ZooKeeper zk;
	
	private NodeReadWatcherHandle watcherHandle;
	
	public IMUserWatcher() {
		
	}
	
	/* (non-Javadoc)
	 * @see org.apache.zookeeper.Watcher#process(org.apache.zookeeper.WatchedEvent)
	 */
	@Override
	public void process(WatchedEvent event) {
		System.out.println("IMUserWatcher.process(WatchedEvent event)");
		try {
			this.zk.exists("/IMUser/ipxs", this);
			this.zk.getChildren("/IMUser/ipxs", this);
		} catch (Exception e) {
			e.printStackTrace(System.out);
		}
		
		String eventPath = event.getPath();
		System.out.println("eventPath = " + eventPath);
		System.out.println("event = " + event);
		
		//TODO 然后要将这个可能新增的IMUser节点加入到本地的结构
		/*
		 * 一般来说，这里只可能出现/IMUser/ipxs下的子节点发生变化。
		 * 除非人为使用zk的客户端强制删除ipxs节点。
		 * 
		 * 所以第一期这里处理/IMUser/ipxs的子节点change事件即可
		 * */
		
		if(event.getType() != EventType.NodeChildrenChanged) {
			System.out.println(event + " 事件没有处理 ");
			return;
		}
		
		Pattern pattern = Pattern.compile("^/IMUser/ipxs$");
		if(pattern.matcher(event.getPath()).find()) {
			try {
				this.watcherHandle.doUserIpxChanged(event.getPath());
			} catch(Exception e) {
				e.printStackTrace(System.out);
			}
		}
	}

	public ZooKeeper getZk() {
		return zk;
	}

	public void setZk(ZooKeeper zk) {
		this.zk = zk;
	}

	public NodeReadWatcherHandle getWatcherHandle() {
		return watcherHandle;
	}

	public void setWatcherHandle(NodeReadWatcherHandle watcherHandle) {
		this.watcherHandle = watcherHandle;
	}
}